﻿using System;
using System.Linq;
using reDoo.Model;

namespace reDoo.Data.Repositories.SQLCompact
{
    public class ProjectRepository : IProjectRepository
    {
        private readonly DatabaseContext databaseContext;

        public ProjectRepository()
        {
            this.databaseContext = new DatabaseContext();
        }

        #region Implementation of IRepository<Project,int>

        /// <summary>
        /// Adds the specified item to the data store.
        /// </summary>
        /// <param name="itemToAdd">The item to add.</param>
        public void Add(Project itemToAdd)
        {
            this.databaseContext.Projects.Add(itemToAdd);
        }

        /// <summary>
        /// Get the item with the specified id from the data store.
        /// </summary>
        /// <param name="id">The id.</param>
        /// <returns></returns>
        public Project GetById(int id)
        {
            return this.databaseContext.Projects.FirstOrDefault(projects => projects.Id.Equals(id));
        }

        /// <summary>
        /// Gets all items from the data store.
        /// </summary>
        /// <returns></returns>
        public IQueryable<Project> GetAll()
        {
            return this.databaseContext.Projects;
        }

        /// <summary>
        /// Finds items specified by the provided filter expression.
        /// </summary>
        /// <param name="filter">The filter.</param>
        /// <returns></returns>
        public IQueryable<Project> Find(Func<Project, bool> filter)
        {
            return this.databaseContext.Projects.Where(filter).AsQueryable();
        }

        /// <summary>
        /// Deletes the item with the specified id from the data store.
        /// </summary>
        /// <param name="id">The id.</param>
        public void DeleteById(int id)
        {
            var project = this.databaseContext.Projects.Single(p => p.Id.Equals(id));
            Delete(project);
        }

        /// <summary>
        /// Deletes the specified item from the data store.
        /// </summary>
        /// <param name="itemToDelete">The item to delete.</param>
        public void Delete(Project itemToDelete)
        {
            this.databaseContext.Projects.Remove(itemToDelete);
        }

        /// <summary>
        /// Save all changes that were made to the repository since the last save within the current
        /// context.
        /// </summary>
        public void SaveChanges()
        {
            this.databaseContext.SaveChanges();
        }

        #endregion
    }
}